import 'dart:async';
import 'dart:io';

import 'package:amap_flutter_location/amap_flutter_location.dart';
import 'package:amap_flutter_location/amap_location_option.dart';
import 'package:xws/models/loc_obj.dart';
import 'package:xws/res/app_configs.dart';

import 'log_util.dart';
import 'tools_util.dart';

/// 定位相关
class _LU {
  _LU._();

  static AMapFlutterLocation? _locationPlugin;
  static StreamSubscription<Map<String, Object>>? _locationListener;

  static bool _isInit = false;

  static void _cancelAMapLinstener() {
    _locationListener?.cancel();
    _locationListener = null;
  }
}

/// 初始化高德地图
Future<bool> _initAMap() async {
  try {
    if (!_LU._isInit) {
      AMapFlutterLocation.updatePrivacyShow(true, true);
      AMapFlutterLocation.updatePrivacyAgree(true);

      /// 获取权限
      final bool p = await getPermission(Permission.locationWhenInUse, openSettings: false);

      if (!p) return false;

      /// android b0f3676032e47fdd6a7f9c820dfacdef
      /// ios d8bd594f3bd1b9aa84207b59b44f2307
      AMapFlutterLocation.setApiKey(AppConfigs.aMapAndroidKey, AppConfigs.aMapIOSKey);

      await delayed(const Duration(milliseconds: 1000));

      _LU._isInit = true;

      return true;
    }

    return true;
  } catch (e) {
    error('初始化高德地图出错:$e');
    return false;
  }
}

/// 获取定位信息
/// retry 失败重试次数
Future<LocObj?> getLocation({
  Duration delay = const Duration(milliseconds: 1000),
  int retry = 3,
}) async {
  try {
    final bool pr = await _initAMap();

    if (!pr) return null;

    LocObj? _locationResult;

    _LU._locationPlugin ??= AMapFlutterLocation();
    _LU._locationPlugin?.setLocationOption(AMapLocationOption(
      onceLocation: Platform.isAndroid,
    ));

    _LU._locationListener ??= _LU._locationPlugin?.onLocationChanged().listen((Map<String, Object> data) {
      _locationResult = LocObj.fromJson(data);
    });

    _LU._locationPlugin?.startLocation();

    await delayed(delay);

    _LU._locationPlugin?.stopLocation();

    clearAMap();

    if (_locationResult == null && retry > 0) {
      return getLocation(retry: retry - 1);
    }

    return _locationResult;
  } catch (e) {
    error('获取定位信息失败:$e');
    return null;
  }
}

/// 清理定位相关
void clearAMap() {
  _LU._cancelAMapLinstener();
  _LU._locationPlugin?.destroy();
  _LU._locationPlugin = null;
}
